import json
import datetime
import time
import threading
import requests
import logging
import sys
from socket import socket, AF_INET, SOCK_STREAM

# 创建一个logger
logger = logging.getLogger('business')
logger.setLevel(logging.DEBUG)

# 创建一个handler，用于写入日志文件
fh = logging.FileHandler('./business.log')
fh.setLevel(logging.DEBUG)

# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

# 给logger添加handler
logger.addHandler(fh)

# 读取配置文件
config = json.loads(open(r'./config.json', encoding='utf-8').read())

monitor = config['monitor']
if monitor == -1:
    sys.exit(0)
name = config['name']
HOST = config["sendIP"]
PORT = config["sendPort"]
ADDR = (HOST, PORT)

logFiles = config['logFiles']

headers = {'Content-Type': 'application/json; charset=UTF-8'}

# thisHour = datetime.datetime.now().hour
thisHour = 17


# 推送日志信息
def sendLogsInfo(allLine):
    send = {
        'modular': '营收',
        'data': allLine
    }
    res = requests.post(url='https://monitor.goafter.xyz/api/log/receive/10', headers=headers, data=json.dumps(send),
                        timeout=60)
    logger.info('推送' + str(len(allLine)) + '条日志，耗时：' + str(res.elapsed.total_seconds()) + '，结果：' + res.text)


def collector(file, modular):
    f = open('log.log', encoding='utf-8')
    lines = []
    while True:
        line = f.readline()
        # 如果读取完
        if not line:
            # 如果数组内还有未推送的数据
            if len(lines) > 0:
                sendLogsInfo(lines)
            break
        try:
            one = json.loads(str(line))
        except ValueError:
            continue
        # 如果数组内数据到达1000时，先推送一次
        if len(lines) >= 1000:
            sendLogsInfo(lines)
            # 清空数组
            lines.clear()
        lines.append(one)


def Distributor():
    global thisHour
    try:
        if ((thisHour + 1) if (thisHour + 1) < 24 else 0) == datetime.datetime.now().hour:
            logger.info('开始推送')
            for one in logFiles:
                threading.Thread(target=collector, args=(one['path'] + '\\' + one['file'], one['modular'])).start()
            thisHour = datetime.datetime.now().hour
    except Exception as r:
        logger.error(str(r))
    finally:
        threading.Timer(300, Distributor).start()





# 心跳
def selfHeart():
    try:
        tcpCliSock = socket(AF_INET, SOCK_STREAM)
        tcpCliSock.connect(ADDR)
        data = {"type": "heart", "monitor": monitor}
        tcpCliSock.send(str(data).encode())
        tcpCliSock.close()
    except Exception as r:
        logger.error(str(r) + '--------selfHeart')
    finally:
        threading.Timer(60, selfHeart, ()).start()


def sendMSGNoSpeak(msg, text):
    sendMSGCore(msg, True, False, text, '')


def sendMSGNoText(msg, speak):
    sendMSGCore(msg, False, True, '', speak)


def sendMSGAllNo(msg):
    sendMSGCore(msg, False, False, '', '')


def sendMSG(msg, text, speak):
    sendMSGCore(msg, True, True, text, speak)


def sendMSGCore(msg, isText, isSpeak, text, speak):
    try:
        tcpCliSock = socket(AF_INET, SOCK_STREAM)
        tcpCliSock.connect(ADDR)
        data = {"type": "forward", "monitor": monitor, "msg": msg, "isText": isText, "isSpeak": isSpeak, "text": text,
                "speak": speak}
        json.dumps(data)
        tcpCliSock.send(str(json.dumps(data)).encode())
        tcpCliSock.close()
    except Exception as r:
        logger.error(str(r) + '--------sendMSG')
        print('请求失败，继续请求')


Distributor()